package utils;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

/**
 * @Description: 通用Servlet
 * @Author one world
 * @Date 2020/8/31 0031 17:27
 */
@WebServlet(name = "BaseServlet")
public abstract class BaseServlet extends HttpServlet {
    private static final Logger logger = LoggerFactory.getLogger(BaseServlet.class);
    /**
     * 根据传入的method参数分发请求
     * @param req
     * @param resp
     * @throws ServletException
     * @throws IOException
     */
    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("UTF-8");
        resp.setCharacterEncoding("UTF-8");
        resp.setHeader("Content-type", "text/html;charset=UTF-8");
        String methodName = req.getParameter("method");
        logger.info("调用Servlet的方法："+methodName);
        if(methodName==null||methodName.trim().isEmpty()){
            logger.info("方法名为空，直接返回");
            return;
        }
        Method method = null;
        Class clazz = this.getClass();
        try {
            method = clazz.getMethod(methodName, HttpServletRequest.class,HttpServletResponse.class);
            String result = (String) method.invoke(this, req,resp);
            if(result==null||result.trim().isEmpty()){
                return;
            }
            if(result.contains(":")){
                int index = result.indexOf(":");
                //获取前缀,通过前缀名区分是转发还是重定向
                String pre = result.substring(0,index);
                //获取后缀
                String after = result.substring(index+1);
               // System.out.println("前缀为："+pre+"后缀为："+after);
                if(pre.equals("f")){
                    req.getRequestDispatcher(after).forward(req, resp);
                }else if(pre.equalsIgnoreCase("r")){
                    resp.sendRedirect(after);
                }else{
                    logger.info("BaseServlet方法错误");
                    return;
                }
            }
        } catch (NoSuchMethodException e) {
            logger.error("BaseServlet子类找不到该方法",e);
        } catch (IllegalAccessException e) {
            logger.error("BaseServlet非法访问异常",e);
        } catch (InvocationTargetException e) {
            logger.error("BaseServlet的InvocationTargetException异常",e);
        }
    }
}
